import  requests ,json,csv,os,datetime
import  pandas as pd
from pyecharts.charts import  Map,Page,Bar,Timeline,Grid,Line
from  pyecharts.components import  Table

from pyecharts.globals import  ThemeType
from pyecharts import options as opts
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.41 Safari/537.36"}
r=requests.get("https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5",headers=headers)
data=json.loads(r.text)
data=json.loads(data["data"])
china_data=data['areaTree'][0]['children']
chinaTotals="确诊人数:"+str(data['chinaTotal']['confirm'])+\
           "疑似人数:"+str(data['chinaTotal']['suspect'])+\
           "死亡人数:"+str(data['chinaTotal']['dead'])+\
           "治愈人数:"+str(data['chinaTotal']['heal'])+\
           "更新日期:"+data['lastUpdateTime']##实时更新
total=[]
tatal_citcy=[]
total_nowConfirm=[]
total_heal=[]
total_confirm=[]
total_dead=[]
for i in range(len(china_data)):
    total.append([
        china_data[i]['name'],
        china_data[i]['total']['nowConfirm'],
        china_data[i]['total']['confirm'],
        china_data[i]['total']['heal'],
        china_data[i]['total']['dead'],#csv数据
    ])
    tatal_citcy.append(china_data[i]['name'])
    total_nowConfirm.append(china_data[i]['total']['nowConfirm'])
    total_confirm.append(china_data[i]['total']['confirm'])
    total_heal.append(china_data[i]['total']['heal'])
    total_dead.append(china_data[i]['total']['dead'])

def save_data():
    with open('./csv/{}.csv'.format(datetime.date.today()),"w",encoding="utf-8") as csv_f :
        writer = csv.writer(csv_f, dialect='excel')
        writer.writerow(["地区","现有确诊","累计确诊","治愈","死亡"])
        for j in total:
            writer.writerow(j) #保存
def view1_data():
    tl = Timeline()
    filename = get_file_name('./csv')
    for i in filename:
        data = pd.read_csv('./csv/{}.csv'.format(i))
        name = list(data['地区'])
        nowConfirm = list(data['现有确诊'])
        confirm = list(data['累计确诊'])
        heal = list(data['治愈'])
        dead = list(data['死亡'])
        c1 = (
            Map()
                .add(series_name="累计确诊", data_pair=[list(z) for z in zip(name, confirm)], maptype="china",
                     is_map_symbol_show=False)
                .set_global_opts(title_opts=opts.TitleOpts(title="中国累计病例（时间：{}）".format(i)),
                                 visualmap_opts=opts.VisualMapOpts(max_=500), )
                .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        )

        tl.add(c1,'{}'.format(i))

    return tl
def view2_data():
    tl = Timeline()
    filename = get_file_name('./csv')
    for i in filename:
        data = pd.read_csv('./csv/{}.csv'.format(i))
        name = list(data['地区'])
        nowConfirm = list(data['现有确诊'])
        confirm = list(data['累计确诊'])
        heal = list(data['治愈'])
        dead = list(data['死亡'])
        bar = (Bar()
           .add_xaxis(name)
           .add_yaxis('现有病例', nowConfirm)
           .add_yaxis('治愈', heal)
           .set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                            markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max", name="500"), ]))
           .set_global_opts(title_opts=opts.TitleOpts(title="目前新增治愈人数"),datazoom_opts=opts.DataZoomOpts() )
        )

        tl.add(bar, "{}".format(i))

    return  tl
def view3_data():
    name=["地区","现有确诊","累计确诊","治愈","死亡"]
    table=(Table()
           .add(name,total)
           .set_global_opts(title_opts=opts.TitleOpts(title="疫情最新状况")))

    return  table

def get_file_name(path_str):
    file_name_list = []
    for root, dirs, files in os.walk(path_str):
        for file in files:
            file_name_list.append(os.path.join(file)[:10])
    return file_name_list
if __name__=='__main__':
    print("爬取中")
    print(chinaTotals)
    print("保存数据中")
    save_data()
    print("正在为你分析图")
    china=view1_data()
    page=Page()
    page.add(china)
    china1=view2_data()
    page.add(china1)
    data1=view3_data()
    page.add(data1)
    page.render("111.html")


